package com.bwie.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.config.IgnoreWhitesConfig;
import com.bwie.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 登录鉴权过滤   验证 token
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreWhitesConfig ignoreWhitesConfig;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 过滤方法
     * @param exchange    请求上下文对象。用来获取请求和响应对象
     * @param chain       网关过滤器链。  用来放行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 判断是否是白名单请求（不拦截的请求）
        // 获取系统配置好的白名单
        List<String> whites = ignoreWhitesConfig.getWhites();
        // 获取当前的请求的URI
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        // 判断当前的请求的URI 是否是白名单 请求
        if (StringUtils.matches(path, whites)) {
            // 是白名单请求 放行
            return chain.filter(exchange);
        }

        // 验证token
        // 获取 token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        // 非空
        if (StringUtils.isBlank(token)) {
            return GatewayUtils.errorResponse(exchange, "token不能为空！");
        }
        // 对不对 合法性
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange, "token不合法！");
        }
        // 有效性
        // 根据token弄到 redis的健
        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) {
            return GatewayUtils.errorResponse(exchange, "token过期！");
        }
        //token续期30分钟
        redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY + userKey,30, TimeUnit.MINUTES);
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 规定过滤器执行顺序
     * @return  数字越小 优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
